import { Injectable } from '@nestjs/common';
import { CreateLoginDto } from './dto/create-login.dto';
import { UserService } from '../user/user.service';
import { AuthService } from '../auth/auth.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class LoginService {
  constructor(
    private readonly userService: UserService,
    private authService: AuthService,
  ) {}

  // 登录
  async login(createLoginDto: CreateLoginDto, session) {
    if (!session?.code) {
      return { code: '000', message: '请重新获取验证码' };
    }

    // 判断用户名密码
    const user = (
      await this.userService.findOneByUserName(createLoginDto.username)
    )[0];
    const isUserAndPwdValid = user && user.password === createLoginDto.password;
    // 判断验证码
    const isCodeValid =
      createLoginDto?.code?.toLowerCase() === session?.code?.toLowerCase();

    if (isUserAndPwdValid && isCodeValid) {
      return this.successLogin(user);
    } else if (!isUserAndPwdValid && isCodeValid) {
      return { code: '000', message: '用户名或密码错误' };
    } else if (isUserAndPwdValid && !isCodeValid) {
      return { code: '000', message: '验证码错误' };
    } else {
      return { code: '000', message: '用户名或密码错误' };
    }
  }

  /**
   * @description: 登录成功的操作
   * @return {*}
   */
  async successLogin(user) {
    const token = await this.authService.creatToken(user);
    const userId = user.id;
    console.log(token, user);
    return { body: { token, userId } };
  }
}
